package ru.spbau.database.group3.parser;

import ru.spbau.database.group3.queryEvaluator.CreateUniqueIndexInstruction;
import ru.spbau.database.group3.queryEvaluator.Instruction;

import java.io.IOException;
import java.util.ArrayList;

/**
 * Created with IntelliJ IDEA.
 * User: stas
 * Date: 1/29/13
 * Time: 7:49 PM

 */
public class CreateUniqueIndexCmd extends abstractCmd {
    public CreateUniqueIndexCmd() {
        super(StringConstants.CREATE_UNIQUE_INDEX);
    }

    @Override
    public Instruction process(String cmd) throws IOException {
        String indexname = getIndexname(cmd);
        String tablename = getTablename(cmd);
        ArrayList<String> cols = getCols(cmd);
        ArrayList<String> orders = getOrders(cmd);
        String type = getType(cmd);
        return new CreateUniqueIndexInstruction(indexname, tablename, cols, orders, type);
    }

    private String getType(String cmd) {
        int begin = cmd.indexOf(StringConstants.USING) + StringConstants.USING.length();
        return cmd.substring(begin).trim();
    }

    private ArrayList<String> getOrders(String cmd) {
        int begin = cmd.indexOf("(", cmd.indexOf(StringConstants.ON)) + 1;
        int end = cmd.lastIndexOf(")");
        String[] col_ord = cmd.substring(begin, end).trim().split(",");
        ArrayList<String> orders = new ArrayList<String>();
        for(String i : col_ord) {
            orders.add(i.trim().split(" ").length > 1 ? i.trim().split(" ")[1] : StringConstants.ASC);
        }
        return orders;
    }

    private ArrayList<String> getCols(String cmd) {
        int begin = cmd.indexOf("(", cmd.indexOf(StringConstants.ON)) + 1;
        int end = cmd.lastIndexOf(")");
        String[] col_ord = cmd.substring(begin, end).trim().split(",");
        ArrayList<String> names = new ArrayList<String>();
        for(String i : col_ord) {
            names.add(i.trim().split(" ").length > 1 ? i.trim().split(" ")[0] : StringConstants.ASC);
        }
        return names;
    }

    private String getTablename(String cmd) {
        int begin = cmd.indexOf(StringConstants.ON) + StringConstants.ON.length();
        int end = cmd.indexOf("(", cmd.indexOf(StringConstants.ON));
        return cmd.substring(begin, end).trim();
    }

    private String getIndexname(String cmd) {
        int begin = StringConstants.CREATE_UNIQUE_INDEX.length();
        int end = cmd.indexOf(StringConstants.ON);
        return cmd.substring(begin, end).trim();
    }
}
